using MediPlatform.Domain.Order;
using MediPlatform.Infeartructure;
using Microsoft.EntityFrameworkCore;
using BCrypt.Net;

namespace MediPlatform.Write.Api.Services
{
    /// <summary>
    /// 认证服务
    /// </summary>
    public class AuthService
    {
        private readonly IBaseRepository<User> _userRepository;
        private readonly JwtService _jwtService;
        private readonly ILogger<AuthService> _logger;

        public AuthService(IBaseRepository<User> userRepository, JwtService jwtService, ILogger<AuthService> logger)
        {
            _userRepository = userRepository;
            _jwtService = jwtService;
            _logger = logger;
        }

        /// <summary>
        /// 验证用户登录
        /// </summary>
        /// <param name="usernameOrEmail">用户名或邮箱</param>
        /// <param name="password">密码</param>
        /// <returns>登录结果</returns>
        public async Task<(bool success, string message, User? user, string? token)> ValidateUserAsync(string usernameOrEmail, string password)
        {
            try
            {
                _logger.LogInformation("尝试验证用户: {UsernameOrEmail}", usernameOrEmail);

                // 查找用户
                var user = await _userRepository.Query()
                    .Where(u => u.Username == usernameOrEmail || u.Email == usernameOrEmail)
                    .FirstOrDefaultAsync();

                if (user == null)
                {
                    _logger.LogWarning("用户不存在: {UsernameOrEmail}", usernameOrEmail);
                    return (false, "用户名或密码不正确", null, null);
                }

                // 验证密码
                bool isPasswordValid = BCrypt.Net.BCrypt.Verify(password, user.PasswordHash);
                if (!isPasswordValid)
                {
                    _logger.LogWarning("密码验证失败: {UsernameOrEmail}", usernameOrEmail);
                    return (false, "用户名或密码不正确", null, null);
                }

                // 生成JWT令牌
                var token = _jwtService.GenerateJwtToken(user.UserId, user.Username, user.Role);

                _logger.LogInformation("用户验证成功: {Username}", user.Username);

                return (true, "登录成功", user, token);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户验证失败: {UsernameOrEmail}", usernameOrEmail);
                return (false, "登录失败，请稍后重试", null, null);
            }
        }
    }
}